// import ModelHandler from "@/request/ModelHandler";
// import {StartConfig} from "@/nodes/start/startConfig";
// import {EndConfig} from "@/nodes/end/endConfig";
// import {ConditionConfig} from "@/nodes/condition/conditionConfig";

// export const api = '/api/canvas/create'

function checkEdgeShape(cell) {
  return cell.shape.includes('edge')
}

export class CanvasCreateModel {
  constructor({graph}) {
    this.graph = graph
  }

  transferDataToServer({canvasData, graphData, eventsData}) {
    let canvas = new CanvasModel().getServerData(canvasData)
    let nodes = []
    let relations = []

    // 节点
    let cells = graphData.cells.filter(cell => !checkEdgeShape(cell))
    // 边
    let edges = graphData.cells.filter(cell => checkEdgeShape(cell))

    cells.forEach(node => {
      const _node = {
        ...node,
        canvasId: canvasData.id
      }
      nodes.push(new NodeModel({graph: this.graph}).getServerData(_node))
    })

    // edges = this.conditionEdgeSort(edges)

    edges.forEach(edge => {
      const _edge = {
        ...edge,
        canvasId: canvasData.id
      }

      relations.push(new RelationModel({graph: this.graph}).getServerData(_edge, graphData))
    })

    // 服务端需要的数据结构
    return {
      canvas,
      nodes,
      relations,
      events: eventsData,
    }
  }

  // 转成 前端页面需要的数据
  transferDataToPage(serverData) {
    let nodes = []
    let edges = []
    serverData.nodes.forEach((node) => {
      nodes.push(new NodeModel({graph: this.graph}).getPageData(node, serverData))
    })

    serverData.relations.forEach((relation) => {
      edges.push(new RelationModel({graph: this.graph}).getPageData(relation, serverData))
    })

    return {
      canvas: serverData.canvas,
      nodes,
      edges,
      events: serverData.events
    }
  }

  // conditionEdgeSort(edges) {
  //   let trueEdgeIndex = edges.findIndex(edge => edge.shape === 'condition-edge' && edge.data.labelValue === true)
  //   let falseEdgeIndex = edges.findIndex(edge => edge.shape === 'condition-edge' && edge.data.labelValue === false) // 排除undefined null之类的可能值
  //   const _edges = [...edges]
  //   if (trueEdgeIndex > -1 && falseEdgeIndex > -1 && trueEdgeIndex > falseEdgeIndex) { // 保证是边在前 否边在后
  //     let tempEdge = _edges[trueEdgeIndex]
  //     _edges[trueEdgeIndex] = _edges[falseEdgeIndex]
  //     _edges[falseEdgeIndex] = tempEdge
  //   }
  //
  //   return _edges
  // }
}

export class CanvasModel {
  constructor() {
    this.canvasStructure = {
      name: null,
      userGroupSymbol: null,
      userGroupId: null,
      middleAccessStatus: null,
      status: null,
      startType: null,
      publishTime: null,
      invalidTime: null,
      limitCount: null,
      cycleType: null,
      cycleValue: null,
      cycleDayTime: null,
      enterCount: null,
      reachCount: null,
      reachBody: null,
      id: null,
      merchantId: null,
      createTime: null,
      updateTime: null,
      deleted: null,
      templateType: null, // 是否为模板
      marketingJourneyInfoId: null, // 模型id
      marketingJourneyStrategyId: null, // 策略id
      backstageTradeId: null, // 行业ID
    }
  }

  getStructure() {
    const _canvasStructure = {...this.canvasStructure}
    return _canvasStructure
  }

  getServerData(pageData) {
    const _canvasStructure = {...this.canvasStructure}
    Object.keys(_canvasStructure).forEach(key => {
      _canvasStructure[key] = pageData[key]
    })

    return _canvasStructure
  }

  getPageData(serverData) {
    const _canvasStructure = {...this.canvasStructure}

    Object.keys(_canvasStructure).forEach(key => {
      _canvasStructure[key] = serverData[key]
    })

    return _canvasStructure
  }
}

export class NodeModel {
  constructor({graph}) {
    this.graph = graph

    this.nodeStructure = {
      canvasId: null,
      name: null,
      x: null,
      y: null,
      baseType: null,
      showType: null,
      anchorPoints: null,
      withinTarget: null,
      executeTimeType: null,
      delayTimeType: null,
      delayTimeValue: null,
      judgeNoType: null,
      delayJudgeNoTimeType: null,
      delayJudgeNoTimeValue: null,
      conditionalExpression: null,
      conditionalOriginal: null,
      reachId: null,
      reachBody: null,
      cycleDayTime: null,
      enterCount: null,
      reachCount: null,
      customId: null,
      id: null,
      merchantId: null,
      createTime: null,
      updateTime: null,
      deleted: null,
    }

    // Cell.Metadata
    this.nodeModel = {
      id: null,
      ports: {
        items: null,
      }, // serverData anchorPoints
      position: {x: null, y: null},
      shape: null,
      label: '',
      zIndex: 1,
      data: {}, // 业务数据
    }
  }

  getServerData(pageData) {
    const _nodeStructure = {...this.nodeStructure}

    pageData.data &&
    pageData.data.dialogData && Object.keys(pageData.data.dialogData).forEach(key => {
      _nodeStructure[key] = pageData.data.dialogData[key]
    })

    _nodeStructure.canvasId = pageData.canvasId
    _nodeStructure.customId = pageData.id
    _nodeStructure.x = pageData.position.x
    _nodeStructure.y = pageData.position.y
    _nodeStructure.baseType = pageData.baseType
    _nodeStructure.showType = pageData.shape
    _nodeStructure.anchorPoints = JSON.stringify(pageData.ports.items.map(anchorItem => ({
      id: anchorItem.id,
      group: anchorItem.group
    })))

    return _nodeStructure
  }

  getPageData(nodeData, serverData) {
    const _nodeModel = {...this.nodeModel}
    _nodeModel.id = nodeData.customId
    _nodeModel.shape = nodeData.showType
    _nodeModel.label = nodeData.name
    _nodeModel.ports.items = JSON.parse(nodeData.anchorPoints)
    _nodeModel.position = {
      x: nodeData.x,
      y: nodeData.y
    }
    _nodeModel.data = {
      dialogData: {...nodeData},
      canvasData: serverData.canvas
    }

    return _nodeModel
  }
}

export class RelationModel {
  constructor({graph}) {
    this.graph = graph

    this.relationStructure = {
      canvasId: null,
      parentPoint: null,
      childrenPoint: null,
      inflection: null,
      weighted: null,
      customSourceId: null,
      sourcePort: null,
      customTargetId: null,
      targetPort: null,
      id: null,
      merchantId: null,
      createTime: null,
      updateTime: null,
      deleted: null,
    }

    this.edgeModel = {
      id: null,
      shape: 'common-edge',
      source: {
        cell: null,
        port: null,
      },
      target: {
        cell: null,
        port: null,
      },
    }
  }

  getServerData(pageData, graphData) {
    const _relationStructure = {...this.relationStructure}

    // 节点
    // const cells = graphData.cells.filter(cell => !checkEdgeShape(cell))
    // 边
    // const edges = graphData.cells.filter(cell => checkEdgeShape(cell))

    // 当前边的source节点
    // const sourceNode = cells.find(cell => cell.id === pageData.source.cell)
    // 当前边的source节点 下的所有边
    // const sourceNodeEdges = edges.filter(edge => edge.source.cell === sourceNode.id)
    // 当前边在source节点下index
    // const sourceIndex = sourceNodeEdges.findIndex(edge => edge.id === pageData.id)

    // 当前边的target节点
    // const targetNode = cells.find(cell => cell.id === pageData.target.cell)
    // 当前边的source节点 下的所有边
    // const targetNodeEdges = edges.filter(edge => edge.target.cell === targetNode.id)
    // 当前边在source节点下index
    // const targetIndex = targetNodeEdges.findIndex(edge => edge.id === pageData.id)
    if (pageData.data && pageData.data.dialogData && pageData.data.dialogData.weighted) {
      _relationStructure.weighted = pageData.data.dialogData.weighted
    }

    _relationStructure.canvasId = pageData.canvasId
    // _relationStructure.parentPoint = sourceIndex // 当前边在源节点的第几条边
    // _relationStructure.childrenPoint = targetIndex // 当前边在终节点的第几条边
    if (pageData.data && pageData.data.dialogData && pageData.data.dialogData.parentPoint) {
      _relationStructure.parentPoint = pageData.data.dialogData.parentPoint // 条件判断、条件选择 中会出现
    }
    // _relationStructure.childrenPoint = targetIndex
    _relationStructure.customSourceId = pageData.source.cell
    _relationStructure.customTargetId = pageData.target.cell
    _relationStructure.sourcePort = pageData.source.port
    _relationStructure.targetPort = pageData.target.port
    _relationStructure.merchantId = pageData.merchantId
    _relationStructure.createTime = pageData.createTime
    _relationStructure.updateTime = pageData.updateTime
    _relationStructure.inflection = JSON.stringify(pageData.vertices)

    return _relationStructure
  }

  getPageData(relation, serverData) {
    const _edgeModel = {...this.edgeModel}

    _edgeModel.id = relation.customId
    _edgeModel.source = {
      cell: relation.customSourceId,
      port: relation.sourcePort,
    }
    _edgeModel.target = {
      cell: relation.customTargetId,
      port: relation.targetPort,
    }
    _edgeModel.vertices = relation.inflection && JSON.parse(relation.inflection) || null
    _edgeModel.data = {
      dialogData: {
        ...relation
      }
    }

    const sourceCellModel = serverData.nodes.find(node => node.customId === relation.customSourceId)
    const sourceCellShape = sourceCellModel.showType
    const sameSourceEdges = serverData.relations.filter(item => item.customSourceId === sourceCellModel.customId)
    const edgeIndex = sameSourceEdges.findIndex(item => item.customId === relation.customId)

    // const specialShapes = ['abtest', 'switcherConcurrent', 'switcherCondition', 'condition']
    _edgeModel.shape = 'common-edge'
    if (sourceCellShape === 'abtest') {
      _edgeModel.shape = `abtest-edge`
    }
    if (sourceCellShape === 'condition') {
      _edgeModel.shape = 'condition-edge'
    }
    if (sourceCellShape === 'switcherConcurrent') {
      _edgeModel.shape = 'switcherConcurrent-edge'
    }
    if (sourceCellShape === 'switcherCondition') {
      _edgeModel.shape = 'switcherCondition-edge'
    }

    if (sourceCellShape === 'abtest') {
      _edgeModel.label = `实验组${edgeIndex + 1}: ${relation.weighted}%`
    }

    if (sourceCellShape === 'condition' && relation.parentPoint === 0) { // 保存时就固定edge的顺序， 是，在前，否，在后
      _edgeModel.label = '是'
    }
    if (sourceCellShape === 'condition' && relation.parentPoint === 1) {
      _edgeModel.label = '否'
    }

    if (sourceCellShape === 'switcherCondition') {
      _edgeModel.label = relation.parentPoint + ''
    }


    return _edgeModel
  }
}
